/// 风筝聊天会话实体模型 - 使用非常规命名避免重复识别
class KiteChatSessionEntity {
  /// 会话唯一标识符
  final String uniqueIdentifier;

  /// 参与用户ID列表（单聊固定为2个用户）
  final List<String> participantPersonaIds;

  /// 最后消息内容
  final String lastMessageContent;

  /// 最后消息时间戳
  final DateTime lastMessageTimestamp;

  /// 最后消息发送者ID
  final String lastMessageSenderId;

  /// 会话创建时间戳
  final DateTime sessionCreationTimestamp;

  /// 未读消息数量
  final int unreadMessageCount;

  const KiteChatSessionEntity({
    required this.uniqueIdentifier,
    required this.participantPersonaIds,
    required this.lastMessageContent,
    required this.lastMessageTimestamp,
    required this.lastMessageSenderId,
    required this.sessionCreationTimestamp,
    this.unreadMessageCount = 0,
  });

  /// 创建空会话实例
  factory KiteChatSessionEntity.createEmptyInstance() {
    return KiteChatSessionEntity(
      uniqueIdentifier: '',
      participantPersonaIds: [],
      lastMessageContent: '',
      lastMessageTimestamp: DateTime.now(),
      lastMessageSenderId: '',
      sessionCreationTimestamp: DateTime.now(),
      unreadMessageCount: 0,
    );
  }

  /// 从Map数据创建会话实例
  factory KiteChatSessionEntity.fromDataMap(Map<String, dynamic> dataMap) {
    return KiteChatSessionEntity(
      uniqueIdentifier: dataMap['uniqueIdentifier'] ?? '',
      participantPersonaIds: List<String>.from(dataMap['participantPersonaIds'] ?? []),
      lastMessageContent: dataMap['lastMessageContent'] ?? '',
      lastMessageTimestamp: DateTime.fromMillisecondsSinceEpoch(
        dataMap['lastMessageTimestamp'] ?? DateTime.now().millisecondsSinceEpoch,
      ),
      lastMessageSenderId: dataMap['lastMessageSenderId'] ?? '',
      sessionCreationTimestamp: DateTime.fromMillisecondsSinceEpoch(
        dataMap['sessionCreationTimestamp'] ?? DateTime.now().millisecondsSinceEpoch,
      ),
      unreadMessageCount: dataMap['unreadMessageCount'] ?? 0,
    );
  }

  /// 转换为Map数据
  Map<String, dynamic> convertToDataMap() {
    return {
      'uniqueIdentifier': uniqueIdentifier,
      'participantPersonaIds': participantPersonaIds,
      'lastMessageContent': lastMessageContent,
      'lastMessageTimestamp': lastMessageTimestamp.millisecondsSinceEpoch,
      'lastMessageSenderId': lastMessageSenderId,
      'sessionCreationTimestamp': sessionCreationTimestamp.millisecondsSinceEpoch,
      'unreadMessageCount': unreadMessageCount,
    };
  }

  /// 复制并修改部分属性
  KiteChatSessionEntity duplicateWithModifications({
    String? uniqueIdentifier,
    List<String>? participantPersonaIds,
    String? lastMessageContent,
    DateTime? lastMessageTimestamp,
    String? lastMessageSenderId,
    DateTime? sessionCreationTimestamp,
    int? unreadMessageCount,
  }) {
    return KiteChatSessionEntity(
      uniqueIdentifier: uniqueIdentifier ?? this.uniqueIdentifier,
      participantPersonaIds: participantPersonaIds ?? this.participantPersonaIds,
      lastMessageContent: lastMessageContent ?? this.lastMessageContent,
      lastMessageTimestamp: lastMessageTimestamp ?? this.lastMessageTimestamp,
      lastMessageSenderId: lastMessageSenderId ?? this.lastMessageSenderId,
      sessionCreationTimestamp: sessionCreationTimestamp ?? this.sessionCreationTimestamp,
      unreadMessageCount: unreadMessageCount ?? this.unreadMessageCount,
    );
  }

  /// 检查是否为有效会话数据
  bool validateEntityIntegrity() {
    return uniqueIdentifier.isNotEmpty &&
        participantPersonaIds.length == 2 &&
        lastMessageContent.isNotEmpty &&
        lastMessageSenderId.isNotEmpty;
  }

  /// 获取对方用户ID
  String getOtherParticipantId(String currentUserId) {
    return participantPersonaIds.firstWhere(
      (id) => id != currentUserId,
      orElse: () => '',
    );
  }

  /// 检查用户是否参与此会话
  bool isUserParticipant(String userId) {
    return participantPersonaIds.contains(userId);
  }

  /// 生成会话ID（基于两个用户ID）
  static String generateSessionId(String userId1, String userId2) {
    final sortedIds = [userId1, userId2]..sort();
    return 'chat_session_${sortedIds[0]}_${sortedIds[1]}';
  }

  /// 获取默认聊天会话数据（以 kite_user_001 为中心）
  static List<KiteChatSessionEntity> getDefaultChatSessions() {
    final now = DateTime.now();
    
    return [
      // 与 kite_user_002 (Windy) 的会话
      KiteChatSessionEntity(
        uniqueIdentifier: generateSessionId('kite_user_001', 'kite_user_002'),
        participantPersonaIds: ['kite_user_001', 'kite_user_002'],
        lastMessageContent: "Can't wait to try that new kite technique you mentioned! 🪁",
        lastMessageTimestamp: now.subtract(const Duration(hours: 2)),
        lastMessageSenderId: 'kite_user_002',
        sessionCreationTimestamp: now.subtract(const Duration(days: 5)),
        unreadMessageCount: 1,
      ),
      
      // 与 kite_user_003 (Soarer) 的会话
      KiteChatSessionEntity(
        uniqueIdentifier: generateSessionId('kite_user_001', 'kite_user_003'),
        participantPersonaIds: ['kite_user_001', 'kite_user_003'],
        lastMessageContent: "Call ended - No answer",
        lastMessageTimestamp: now.subtract(const Duration(hours: 6)),
        lastMessageSenderId: 'system',
        sessionCreationTimestamp: now.subtract(const Duration(days: 3)),
        unreadMessageCount: 0,
      ),
      
      // 与 kite_user_004 (Breeze) 的会话
      KiteChatSessionEntity(
        uniqueIdentifier: generateSessionId('kite_user_001', 'kite_user_004'),
        participantPersonaIds: ['kite_user_001', 'kite_user_004'],
        lastMessageContent: "The wind conditions tomorrow look perfect for flying! 🌬️",
        lastMessageTimestamp: now.subtract(const Duration(hours: 12)),
        lastMessageSenderId: 'kite_user_001',
        sessionCreationTimestamp: now.subtract(const Duration(days: 7)),
        unreadMessageCount: 0,
      ),
      
      // 与 kite_user_005 (Glider) 的会话
      KiteChatSessionEntity(
        uniqueIdentifier: generateSessionId('kite_user_001', 'kite_user_005'),
        participantPersonaIds: ['kite_user_001', 'kite_user_005'],
        lastMessageContent: "Call ended - No answer",
        lastMessageTimestamp: now.subtract(const Duration(days: 1)),
        lastMessageSenderId: 'system',
        sessionCreationTimestamp: now.subtract(const Duration(days: 2)),
        unreadMessageCount: 0,
      ),
    ];
  }
}
